﻿using System;
using System.Collections;
using System.Threading.Tasks;
using Cinemachine;
using UnityEngine;
using UnityEngine.UIElements;

public class ChessPanel : MonoBehaviour
{
    public Lattice currentSpotlightLattice = null;
    public UIDocument uiDoc;
    public VisualTreeAsset buildingBtn1;
    public VisualTreeAsset buildingBtn2;

    public VisualTreeAsset soliderBtn2;
    public VisualTreeAsset detailAsset;

    private VisualElement rootElement,detailRootElement,card,chessBg,chess,skill;

    private Label hpText, attackText,skillDescription;

    private Button button1, button2;

    public UIDocument detailPanel;


    private void OnEnable()
    {
        EventCenter.GetInstance().AddEventListener<Lattice>("ShowChessUI", SpotlightLatticeChanged);
        EventCenter.GetInstance().AddEventListener<Lattice>("ShowChessUI", ShowChessDetailUI);
        EventCenter.GetInstance().AddEventListener("HideChessUI", ClearSpotlightLattice);
    }

    

    private void OnDisable()
    {
        EventCenter.GetInstance().RemoveEventListener<Lattice>("ShowChessUI", SpotlightLatticeChanged);
        EventCenter.GetInstance().RemoveEventListener<Lattice>("ShowChessUI", ShowChessDetailUI);
        EventCenter.GetInstance().RemoveEventListener("HideChessUI", ClearSpotlightLattice);
    }

    private void ShowChessDetailUI(Lattice lattice)
    {
        currentSpotlightLattice = lattice;
        var c = currentSpotlightLattice.chess;
            
        detailPanel.visualTreeAsset = detailAsset;
        detailRootElement = detailPanel.rootVisualElement;
        detailRootElement.style.display = DisplayStyle.Flex;
        card =  detailRootElement.Q<VisualElement>(nameof(Card));
        card.style.backgroundImage = new StyleBackground(c.chessDate.cardBackgroundSprite);
        chessBg = detailRootElement.Q<VisualElement>("ChessBg");
        chessBg.style.backgroundImage =  new StyleBackground(c.chessDate.chessBackgroundSprite);
        chess = detailPanel.rootVisualElement.Q<VisualElement>(nameof(Chess));
        chess.style.backgroundImage = new StyleBackground(c.chessDate.chessSprite);
        hpText =  detailRootElement.Q<Label>("HpText");
        attackText = detailRootElement.Q<Label>("AttackText");
            
        hpText.text = c.ChessDetail.TotalHp.ToString();
        skill = detailRootElement.Q<VisualElement>("Skill");
        skillDescription = detailRootElement.Q<Label>("Descirbe");

        if (c.chessDate.skill.Count == 0)
        {
            skill.style.display = DisplayStyle.None;
        }
        else
        {
            skill.style.display = DisplayStyle.Flex;
            print(c.chessDate.description);
            skillDescription.text = c.chessDate.description;
        }
        if (currentSpotlightLattice.chessDate.chessType == ChessType.Building)
        {
            BuildingChessDateSO date = currentSpotlightLattice.chessDate as BuildingChessDateSO;
            
            attackText.text = date.soldierChessDates.Count.ToString();
        }
        if (currentSpotlightLattice.chessDate.chessType == ChessType.Soldier)
        {
            attackText.text = c.ChessDetail.Attack.ToString();
        }
    }
    private void SpotlightLatticeChanged(Lattice lattice)
    {
        if(lattice.chess.GetChessSide() != ChessSide.Player1) return;
        currentSpotlightLattice = lattice;
        if (currentSpotlightLattice.chessDate.chessType == ChessType.Building)
        {
            BuildingChessDateSO date = currentSpotlightLattice.chessDate as BuildingChessDateSO;
            var c = currentSpotlightLattice.chess;
            if (date.soldierChessDates.Count == 1)
            {
                uiDoc.visualTreeAsset = buildingBtn1;
                rootElement = uiDoc.rootVisualElement;
                button1 = rootElement.Q<Button>("Button1");
                SetInteractable(button1,true);
                button1.clicked += ClickBuildingBtn1;
                
                button1.style.backgroundImage =
                    new StyleBackground(date.soldierChessDates[0].chessSprite);

                StartCoroutine(MoveToWorldPosition(rootElement, (lattice.transform.position), Vector2.one));
                rootElement.style.display = DisplayStyle.Flex;
                
                SetInteractable(button1,UpdateChessState(date.soldierChessDates[0],lattice.chess.GetChessSide()));
            }
            else if (date.soldierChessDates.Count == 2)
            {
                
                    uiDoc.visualTreeAsset = buildingBtn2;
                    rootElement = uiDoc.rootVisualElement;
                    button1 = rootElement.Q<Button>("Button1");
                    button2 = rootElement.Q<Button>("Button2");
                    SetInteractable(button1,true);
                    SetInteractable(button2,true);
                    button1.clicked += ClickBuildingBtn1;
                    button2.clicked += ClickBuildingBtn2;
                

                button1.style.backgroundImage =
                    new StyleBackground(date.soldierChessDates[0].chessSprite);
                button2.style.backgroundImage =
                    new StyleBackground(date.soldierChessDates[1].chessSprite);

                StartCoroutine(MoveToWorldPosition(rootElement, (lattice.transform.position), Vector2.zero));
                rootElement.style.display = DisplayStyle.Flex;
                
                SetInteractable(button1,UpdateChessState(date.soldierChessDates[0],lattice.chess.GetChessSide()));
                SetInteractable(button2,UpdateChessState(date.soldierChessDates[1],lattice.chess.GetChessSide()));
            }
            
        }

        if (currentSpotlightLattice.chessDate.chessType == ChessType.Soldier)
        {
            SoldierChessDateSO date = currentSpotlightLattice.chessDate as SoldierChessDateSO;
            var c = currentSpotlightLattice.chess;
            
            uiDoc.visualTreeAsset = soliderBtn2;
            rootElement = uiDoc.rootVisualElement;
            button1 = rootElement.Q<Button>("Button1");
            button2 = rootElement.Q<Button>("Button2");
            SetInteractable(button1,true);
            SetInteractable(button2,true);
            button1.clicked += ClickMoveBtn;
            button2.clicked += ClickAttackBtn;
            

            StartCoroutine(MoveToWorldPosition(rootElement, (lattice.transform.position), Vector2.zero));
            rootElement.style.display = DisplayStyle.Flex;
            
            
            SetInteractable(button1,currentSpotlightLattice.chess.ChessDetail.CanMove);
            if (currentSpotlightLattice.chess.ChessDetail.CanUse == false)
            {
                SetInteractable(button1,false);
                SetInteractable(button2,false);
            }
            
            detailPanel.visualTreeAsset = detailAsset;
            detailRootElement = detailPanel.rootVisualElement;
            detailRootElement.style.display = DisplayStyle.Flex;
            card =  detailRootElement.Q<VisualElement>(nameof(Card));
            card.style.backgroundImage = new StyleBackground(date.cardBackgroundSprite);
            chessBg = detailRootElement.Q<VisualElement>("ChessBg");
            chessBg.style.backgroundImage =  new StyleBackground(date.chessBackgroundSprite);
            chess = detailPanel.rootVisualElement.Q<VisualElement>(nameof(Chess));
            chess.style.backgroundImage = new StyleBackground(date.chessSprite);
            hpText =  detailRootElement.Q<Label>("HpText");
            attackText = detailRootElement.Q<Label>("AttackText");
            
            hpText.text = c.ChessDetail.TotalHp.ToString();
            attackText.text = c.ChessDetail.Attack.ToString();
            
            skill = detailRootElement.Q<VisualElement>("Skill");
            skillDescription = detailRootElement.Q<Label>("Descirbe");

            if (date.description == null)
            {
                skill.style.display = DisplayStyle.None;
            }
            else
            {
                skill.style.display = DisplayStyle.Flex;
                print(date.description);
                skillDescription.text = date.description;
            }
        }
    }
    
    public void SetInteractable(Button myButton,bool state)
    {
        myButton.SetEnabled(state);
    
        if (!state)
        {
            // 强制移除所有交互状态
            myButton.RemoveFromClassList("button--hover");
            myButton.RemoveFromClassList("button--active");
        
            // 立即重置变换
            myButton.style.translate = new StyleTranslate(new Translate(0, 0, 0));
            myButton.style.scale = new StyleScale(Vector3.one);
        
            // 确保禁用样式覆盖
            myButton.AddToClassList("turnButton--disabled");
        }
        else
        {
            myButton.AddToClassList("turnButton--hover");
            myButton.AddToClassList("turnButton--active");
            myButton.RemoveFromClassList("turnButton--disabled");
        }
    
        // 强制重绘
        myButton.MarkDirtyRepaint();
    }

    private void ClearSpotlightLattice()
    {
        if (rootElement != null)
        {
            rootElement.style.display = DisplayStyle.None;
        }
        if (detailRootElement != null)
        {
            detailRootElement.style.display = DisplayStyle.None;
        }

        currentSpotlightLattice = null;
    }

    private IEnumerator MoveToWorldPosition(VisualElement element, Vector3 worldPosition, Vector2 size)
    {
        yield return 1;
        var p = worldPosition - Camera.main.transform.position;

        // 使用 RuntimePanelUtils 处理 UI 缩放和分辨率自适应
        Vector2 uiPosition = RuntimePanelUtils.CameraTransformWorldToPanel(element.panel, worldPosition, Camera.main);

        // 设置 UI 元素位置（注意 UIToolkit 的坐标系原点在左上角）
        element.style.left = uiPosition.x;
        element.style.top = uiPosition.y;
    }

    #region 点击建筑的UI按钮逻辑

    private void ClickBuildingBtn1()
    {
        if(Settings.isPlayerTurn == false || currentSpotlightLattice.chessDate.resourcesPoint>PlayerResourcesManager.GetInstance().Player1Resources)
            return;
        _ = PlaceChessAsync(0);
    }

    private void ClickBuildingBtn2()
    {
        if(Settings.isPlayerTurn == false || currentSpotlightLattice.chessDate.resourcesPoint>PlayerResourcesManager.GetInstance().Player1Resources)
            return;
        _ = PlaceChessAsync(1);
    }

    private async Task PlaceChessAsync(int i)
    {
        BuildingChessDateSO date = currentSpotlightLattice.chessDate as BuildingChessDateSO;
        Lattice l = currentSpotlightLattice;
        
        _ = await HandleUseManager.GetInstance()
            .PlacedChessAsync(l,date.soldierChessDates[i].placedPositions, date.soldierChessDates[i], Settings.canPlaced);
    }

    #endregion

    #region 点击士兵的UI按钮逻辑

    private void ClickMoveBtn()
    {
        if(Settings.isPlayerTurn == false)
            return;
        _ = MoveChessAsync();
    }

    private async Task MoveChessAsync()
    {
        SoldierChessDateSO date = currentSpotlightLattice.chessDate as SoldierChessDateSO;
        Chess chess = currentSpotlightLattice.chess;
        Lattice originLattice = currentSpotlightLattice;
        Lattice moveToLattice = await HandleUseManager.GetInstance()
            .MoveChessAsync(originLattice,date.moveRange, date, Settings.canPlaced);
        
        if(!moveToLattice)
            return;
        
        ClickManager.GetInstance().MoveChess(moveToLattice);
        
        
        bool isSuccess = await HandleUseManager.GetInstance()
            .AttackChessAsync(moveToLattice, date);
        
        //移动成功后攻击,如果攻击成功转换回合
        //如果失败,回退到移动前的地方
        if(isSuccess)
        {
            EventCenter.GetInstance().EventTrigger<GameEvent>(SkillEventName.EventChangeChess.ToString(),new ChangeEvent(chess));
            EventCenter.GetInstance().EventTrigger<GameEvent>(SkillEventName.EventMoveChess.ToString(),new moveEvent(chess));
            EventCenter.GetInstance().EventTrigger("Player1TurnEnd");
            ClickManager.GetInstance().MoveChess(null);
            return;
        }
        
        
        ChessManager.GetInstance().MoveChess(moveToLattice.position,originLattice.position);
    }

    private void ClickAttackBtn()
    {
        if(Settings.isPlayerTurn == false)
            return;
        _ = AttackAsync();
    }
    
    private async Task AttackAsync()
    {
        //TODO:交互逻辑还得优化
        SoldierChessDateSO date = currentSpotlightLattice.chessDate as SoldierChessDateSO;
        Lattice l = currentSpotlightLattice;
        
        bool isSuccess = await HandleUseManager.GetInstance()
            .AttackChessAsync(l, date);
        
        if(isSuccess)
        {
            EventCenter.GetInstance().EventTrigger("Player1TurnEnd");
            ClickManager.GetInstance().MoveChess(null);
        }
        
    }

    #endregion
    
    
    public bool UpdateChessState(SoldierChessDateSO date,ChessSide side){
        return date.resourcesPoint <= (side == ChessSide.Player1
            ? PlayerResourcesManager.GetInstance().Player1Resources
            : PlayerResourcesManager.GetInstance().Player2Resources);
    }
}